<?php


namespace App\Http\Controllers\Api;


use App\Http\Controllers\Backend\BaseController;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use App\Services\Base\Services\ConfigService;
use App\Services\Base\Interfaces\ConfigServiceInterface;



class AliyunController extends BaseController
{


    public function aliyunCreateVideoToken(Request $request, ConfigServiceInterface $configService)
    {

        $title = $request->input('title');
        $filename = $request->input('filename');
        try {
            aliyun_sdk_client();

            $config = $configService->getAliyunVodConfig();

            $result = \AlibabaCloud\Client\AlibabaCloud::rpc()
                ->host($config['host'])
                ->product('Vod')
                ->version('2017-03-21')
                ->action('CreateUploadVideo')
                ->options([
                    'query' => [
                        'Title' => $title,
                        'FileName' => $filename,
                    ]
                ])
                ->request();

            return $this->successData([
                'upload_auth' => $result['UploadAuth'],
                'upload_address' => $result['UploadAddress'],
                'video_id' => $result['VideoId'],
                'request_id' => $result['RequestId'],
            ]);
        } catch (Exception $exception) {

            exception_record($exception);

            return $this->error($exception->getMessage());
        }
    }

    public function aliyunRefreshVideoToken(Request $request, ConfigServiceInterface $configService)
    {
        /**
         * @var ConfigService $configService
         */

        $videoId = $request->input('video_id');

        try {
            aliyun_sdk_client();

            $config = $configService->getAliyunVodConfig();

            $result = \AlibabaCloud\Client\AlibabaCloud::rpc()
                ->product('Vod')
                ->host($config['host'])
                ->version('2017-03-21')
                ->action('RefreshUploadVideo')
                ->options([
                    'query' => [
                        'VideoId' => $videoId,
                    ]
                ])
                ->request();

            return $this->successData([
                'upload_auth' => $result['UploadAuth'],
                'upload_address' => $result['UploadAddress'],
                'video_id' => $result['VideoId'],
                'request_id' => $result['RequestId'],
            ]);
        } catch (Exception $exception) {
            Log::info('refresh_token' . $exception->getMessage());
            exception_record($exception);

            return $this->error($exception->getMessage());
        }
    }

    public function aliyunCreateImageToken(Request $request, ConfigServiceInterface $configService)
    {
        /**
         * @var ConfigService $configService
         */

        $title = $request->input('title', 'media_'.time());

        try {
            aliyun_sdk_client();

            $config = $configService->getAliyunVodConfig();

            $result = \AlibabaCloud\Client\AlibabaCloud::rpc()
                ->product('Vod')
                ->host($config['host'])
                ->version('2017-03-21')
                ->action('CreateUploadImage')
                ->options([
                    'query' => [
                        'Title' => $title,
                        'ImageType' => 'default'
                    ]
                ])
                ->request();

            return $this->successData([
                'upload_auth' => $result['UploadAuth'],
                'upload_address' => $result['UploadAddress'],
                'image_id' => $result['ImageId'],
                'request_id' => $result['RequestId'],
                'file_url' => $result['FileURL'],
                'image_url' => $result['ImageURL']
            ]);
        } catch (Exception $exception) {
            Log::info('upload_image_token' . $exception->getMessage());
            exception_record($exception);

            return $this->error($exception->getMessage());
        }
    }


    /**
     * 获取播放信息
     * @param Request $request
     * @param ConfigServiceInterface $configService
     * @return JsonResponse
     */
    public function getPlayInfo(Request $request, ConfigServiceInterface $configService)
    {
        $videoId = $request->input('video_id');

        try {
            aliyun_sdk_client();

            $config = $configService->getAliyunVodConfig();

            $result = \AlibabaCloud\Client\AlibabaCloud::rpc()
                ->product('Vod')
                ->host($config['host'])
                ->version('2017-03-21')
                ->action('GetPlayInfo')
                ->options([
                    'query' => [
                        'VideoId' => $videoId,
                        'Formats' => 'mp4'
                    ]
                ])
                ->request();
            $playInfo = $result['PlayInfoList']['PlayInfo'];
            $rows = [];
            foreach ($playInfo as $item) {
                $rows[] = [
                    'format' => $item['Format'],
                    'url' => $url = strpos($item['PlayURL'], '?') !== false ? substr($item['PlayURL'], 0, strpos($item['PlayURL'], '?')) : $item['PlayURL'],
                    'duration' => $item['Duration'],
                    'name' => $item['Height'],
                ];
            }
            return $this->successData($rows);
        } catch (Exception $exception) {
            exception_record($exception);

            return $this->error($exception->getMessage());
        }

    }

    /**
     * 获取播放信息
     * @param Request $request
     * @param ConfigServiceInterface $configService
     * @return JsonResponse
     */
    public function getVideoList(Request $request, ConfigServiceInterface $configService)
    {
        try {
            aliyun_sdk_client();

            $config = $configService->getAliyunVodConfig();

            $result = \AlibabaCloud\Client\AlibabaCloud::rpc()
                ->product('Vod')
                ->host($config['host'])
                ->version('2017-03-21')
                ->action('getVideoList')
                ->options([
                    'query' => [

                    ]
                ])
                ->request();
            $videos = $result['VideoList']['Video'];
            return $this->successData(compact('videos'));
        } catch (Exception $exception) {
            exception_record($exception);

            return $this->error($exception->getMessage());
        }

    }

    public function getImageList(Request $request, ConfigServiceInterface $configService)
    {
        try {
            aliyun_sdk_client();

            $config = $configService->getAliyunVodConfig();

            $result = \AlibabaCloud\Client\AlibabaCloud::rpc()
                ->product('Vod')
                ->host($config['host'])
                ->version('2017-03-21')
                ->action('SearchMedia')
                ->options([
                    'query' => [
                        "SearchType" => 'image'
                    ]
                ])
                ->request();
            $medias = $result['MediaList'];
            $imageIds = '';

// 遍历每个对象，提取ImageId字段的值并拼接成字符串
            foreach ($medias as $index => $media) {
                // 拼接ImageId到字符串，如果不是第一个元素，则加上逗号
                $imageIds .= ($index > 0 ? ',' : '') . $media['Image']['ImageId'];
            }
            $result = \AlibabaCloud\Client\AlibabaCloud::rpc()
                ->product('Vod')
                ->host($config['host'])
                ->version('2017-03-21')
                ->action('GetImageInfos')
                ->options([
                    'query' => [
                        "ImageIds" => $imageIds
                    ]
                ])
                ->request();
            $images = $result['ImageInfo'];
            return $this->successData(compact('images'));
        } catch (Exception $exception) {
            exception_record($exception);

            return $this->error($exception->getMessage());
        }

    }



}
